package jjn.carl.dp;

import java.util.Scanner;

/**
 * @author Jiang Jining
 * @since 2023-08-13 16:39
 */
public class LeetCode1049 {
    public int lastStoneWeightII(int[] stones) {
        int totalWeight = 0;
        for (int stone : stones) {
            totalWeight += stone;
        }
        int target = totalWeight / 2;
        int[] dp = new int[3001];
        for (int i = 0; i < stones.length; i++) {
            for (int j = target; j >= stones[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        return totalWeight - 2 * dp[target];
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = scanner.nextInt();
        int[] stones = new int[total];
        for (int i = 0; i < total; i++) {
            stones[i] = scanner.nextInt();
        }
        int stoneWeight = new LeetCode1049().lastStoneWeightII(stones);
        System.out.println(stoneWeight);
    }
}
